#include "PhysicShape.h"

#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>


PhysicShape::PhysicShape()
{

}

PhysicShape::~PhysicShape()
{

}


PhysicShape::PhysicShape(const PhysicShape&)
{

}

PhysicShape PhysicShape::operator=(PhysicShape const&)
{
	return PhysicShape();
}

bool PhysicShape::Initialize(std::string pFile, PhysicShapeType pType)
{
	if(pType == BvhTriangle || pType == Triangle)
	{
		btTriangleMesh* cTriangleMesh  = new btTriangleMesh();

		Assimp::Importer Importer;
		const aiScene* pScene = Importer.ReadFile(pFile, aiProcess_Triangulate);

		for (unsigned int i = 0 ; i < pScene->mNumMeshes ; i++) {
			const aiMesh* paiMesh = pScene->mMeshes[i];

			for(unsigned int i = 0;i < paiMesh->mNumFaces;i++)
			{
				for(unsigned int  j = 0; j < paiMesh->mFaces[i].mNumIndices;j++)
				{
					aiVector3D v1 = paiMesh->mVertices[paiMesh->mFaces[i].mIndices[0]];
					aiVector3D v2 = paiMesh->mVertices[paiMesh->mFaces[i].mIndices[1]];
					aiVector3D v3 = paiMesh->mVertices[paiMesh->mFaces[i].mIndices[2]];

					cTriangleMesh->addTriangle(btVector3(v1.x, v1.y, v1.z),
											   btVector3(v2.x, v2.y, v2.z),
											   btVector3(v3.x, v3.y, v3.z));
				}
			}
		}
		if(pType == BvhTriangle)
		{
			btBvhTriangleMeshShape* s = new btBvhTriangleMeshShape(cTriangleMesh,true, true);
			s->buildOptimizedBvh();
			mShape = s;
		}
		else if(pType == Triangle)
		{
			mShape = new btConvexTriangleMeshShape(cTriangleMesh,true);
		}
	}

	return true;
}

void PhysicShape::Uninit()
{

}

void PhysicShape::CalculateLocalInertia(btScalar mass, btVector3 &fallInertia)
{
	mShape->calculateLocalInertia(mass, fallInertia);
}

btCollisionShape* PhysicShape::getShape()
{
	return mShape;
}